package com.stlm2.controller.imageverify;

import com.stlm2.core.redis.RedisClient;
import com.stlm2.util.ValidateCode;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Set;

/**
 * Created by apple on 2017/9/17.
 */
@Controller
@RequestMapping("/imageVerifyC")
public class ImageVerify {
    /**
     * 响应验证码页面
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/validateCode.json",produces="application/json;charset=UTF-8")
    public String validateCode(HttpServletRequest request, HttpServletResponse response,String userName) throws Exception{

        /*
        * 获取IP地址
        * */
        JedisPool pool = null;
        Jedis jedis = null;
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();

        // 设置响应的类型格式为图片格式
        response.setContentType("image/jpeg");
        //禁止图像缓存。
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        HttpSession session = request.getSession();

        ValidateCode vCode = new ValidateCode(120,40,5,100);
        Set<String> validateCodeList=jedis.keys("CRMValidateCode:" + userName +"*");
            if(validateCodeList.size()>0){
                for (String validateCode1:validateCodeList) {
                    jedis.del(validateCode1);
                }
            }
                StringBuffer key=new StringBuffer();
                key.append("CRMValidateCode:");
                key.append(userName + ":");
                key.append(vCode.getCode().toLowerCase());
                jedis.incrBy(key.toString(),0);
                jedis.expire(key.toString(),60);
//                System.out.println("CRMValidateCode:" + mobile + ":"+ vCode.getCode() + "----" + vCode.getCode().toLowerCase());

        session.setAttribute("code", vCode.getCode());
        vCode.write(response.getOutputStream());

        } catch (Exception e) {
            e.printStackTrace();
            return  null;
        }finally {
            pool.returnResource(jedis);
        }
        return null;
    }

    /**
     * 验证图形验证码
     * @param  userName：用户名
     *   @param  validateCode:验证码
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/verifyCode.json",produces="application/json;charset=UTF-8")
    public String verifyCode(ModelMap modelMap,String userName ,String validateCode){
        JedisPool pool = null;
        Jedis jedis = null;
        if(!NumberUtils.isDigits(userName)){
            return  CodeContent.getModelByCode(0, "请输入用户名", modelMap);
        }
        if(StringUtils.isEmpty(validateCode)){
            return  CodeContent.getModelByCode(0, "请输入用户名", modelMap);
        }
        try {
            pool = RedisClient.getPool();
            jedis = pool.getResource();
            validateCode=StringUtils.trimAllWhitespace(validateCode);
            StringBuffer key=new StringBuffer();
            key.append("ValidateCode:");
            key.append(userName + ":");
            key.append(validateCode.toLowerCase());
            boolean boo =jedis.exists(key.toString());
            if(boo){
                modelMap.put("verifyCode",true);
                modelMap.put("code",1);
                modelMap.put("msg","success");
                return  new JSONObject(modelMap).toString();
            }else {
                modelMap.put("verifyCode",false);
                modelMap.put("code",1);
                modelMap.put("msg","success");
                return  new JSONObject(modelMap).toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CodeContent.getModelByCode(0,"验证失败", modelMap);
        }finally {
            pool.returnResource(jedis);
        }
    }
//    /**
//     * 判断是否请求过图形验证码
//     * @param  mobile：手机号
//     *
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value="/ifCode",produces="application/json;charset=UTF-8")
//    public String ifCode(ModelMap modelMap,String mobile ){
//        JedisPool pool = null;
//        Jedis jedis = null;
//        if(!NumberUtils.isDigits(mobile)){
//            return  CodeContent.getModelByCode(0, "请输入手机号", modelMap);
//        }
//        try {
//            pool = RedisClient.getPool();
//            jedis = pool.getResource();
//            Set<String> validateCodeList=jedis.keys("ValidateCode:" + mobile +":true*");
//            if(validateCodeList.size()>0){
//                modelMap.put("ifCode",true);
//                modelMap.put("code",1);
//                modelMap.put("msg","success");
//                return  new JSONObject(modelMap).toString();
//            }else {
//                modelMap.put("ifCode",false);
//                modelMap.put("code",1);
//                modelMap.put("msg","success");
//                return  new JSONObject(modelMap).toString();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            return CodeContent.getModelByCode(0,"验证失败", modelMap);
//        }finally {
//            pool.returnResource(jedis);
//        }
//    }
}
